﻿Xrm = window.Xrm || { __namespace: true };
Xrm.ShowDupes = Xrm.ShowDupes || { __namespace: true };
Xrm.ShowDupes.createMessage = "This new record might be a duplicate of an existing record. Review the potential duplicates and decide whether to save the record anyway.";
Xrm.ShowDupes.updateMessage = "This record might be a duplicate of an existing record. Review the potential duplicates and decide whether to update the record anyway.";
Xrm.ShowDupes.recordTypes = {};
Xrm.ShowDupes.selectedDuplicates = [];
Xrm.ShowDupes.url = null;

var numberOfDuplicates, action;

$(function () {
    $("#saveRecord").on("click", Xrm.ShowDupes.Save);
    $("#cancel").on("click", Xrm.ShowDupes.Cancel);
    $("#neverShow").on("click", Xrm.ShowDupes.NeverShow);
    $("#recordType").on("change", Xrm.ShowDupes.UpdateDuplicateList);

    if (action === "create") {
        $("#message").text(Xrm.ShowDupes.createMessage);
    }
    else {
        $("#message").text(Xrm.ShowDupes.updateMessage);
    }

    Xrm.ShowDupes.url = dialogArguments.url;

    Xrm.ShowDupes.GetRecordTypes();
    Xrm.ShowDupes.CurrentDetail();
    Xrm.ShowDupes.UpdateDuplicateList();

    if (dialogArguments.neverAllowSave === true) {
        $("#saveRecord").hide();
        $("#neverShow").hide();
        $("#neverSaveMessage").show();
    }
});

Xrm.ShowDupes.UpdateDuplicateList = function () {
    Xrm.ShowDupes.selectedDuplicates = [];
    for (var x = 0; x < dialogArguments.records.length; x++) {
        if (dialogArguments.records[x].logicalName === $("#recordType option:selected").val()) {
            Xrm.ShowDupes.selectedDuplicates.push(dialogArguments.records[x]);
        }
    }
    Xrm.ShowDupes.RecordsDetails();
};

Xrm.ShowDupes.GetRecordTypes = function () {
    $(dialogArguments.records).each(function () {
        if ($.inArray(this.logicalName, Xrm.ShowDupes.recordTypes) === -1) {
            Xrm.ShowDupes.recordTypes[this.logicalName] = (Xrm.ShowDupes.recordTypes[this.logicalName] || 0) + 1;
        }
    });

    $.each(Xrm.ShowDupes.recordTypes, function (key, value) {
        $("#recordType").append('<option value="' + key + '" ' + (key === dialogArguments.current.logicalName ? 'selected="selected"' : '') +
            '>' + "(" + value + ") " + key + '</option>');
    });
};

Xrm.ShowDupes.Save = function () {
    window.returnValue = ["save", "0"];
    window.close();
};

Xrm.ShowDupes.Cancel = function () {
    window.returnValue = ["cancel", "0"];
    window.close();
};

Xrm.ShowDupes.NeverShow = function () {
    window.returnValue = ["nevershow", "0"];
    window.close();
};

Xrm.ShowDupes.OpenRecord = function (entityType, id) {
    var url = Xrm.ShowDupes.url + "/main.aspx?etn=" + entityType + "&pagetype=entityrecord&id=%7B" + id + "%7D";
    window.open(url, "", "width=1000,height=800");
};

//Displays the duplicate record detail
//Not displaying a link to the potential duplicate record in the event of a save & close, currently facing an issue 
//where the record will not open properly if the user navigates away from the page and attempts to open a potential duplicate
Xrm.ShowDupes.RecordsDetails = function () {
    var html = '<table><thead><tr>';
    for (var i = 0; i < Xrm.ShowDupes.selectedDuplicates[0].attributes.length; i++) {
        html += '<th>' + Xrm.ShowDupes.selectedDuplicates[0].attributes[i].Label + '</th>';
    }
    html += '</tr></thead><tbody>';
    for (var j = 0; j < Xrm.ShowDupes.selectedDuplicates.length; j++) {
        html += '<tr>';
        html += '<td>';
        if (dialogArguments.saveModeCode !== "saveandclose") {
            html += '<a id="' + Xrm.ShowDupes.selectedDuplicates[j].id + '" onClick="Xrm.ShowDupes.OpenRecord(\'' +
                Xrm.ShowDupes.selectedDuplicates[j].logicalName + '\', this.id)">';
        }
        html += Xrm.ShowDupes._getDisplayValue(Xrm.ShowDupes.selectedDuplicates[j].attributes[0]) + '</td>';
        if (dialogArguments.saveModeCode !== "saveandclose") {
            html += "</a>";
        }
        html += "</td>";
        for (var k = 1; k < Xrm.ShowDupes.selectedDuplicates[j].attributes.length; k++) {
            html += '<td>' + Xrm.ShowDupes._getDisplayValue(Xrm.ShowDupes.selectedDuplicates[j].attributes[k]) + '</td>';
        }
        html += "</tr>";
    }
    html += '</tbody><tfoot><tr></tr></tfoot></table>';
    $('#records').html(html);
};

//Displays the current record detail
Xrm.ShowDupes.CurrentDetail = function () {
    var html = '<table><thead><tr>';
    for (var i = 0; i < dialogArguments.current.attributes.length; i++) {
        html += '<th>' + dialogArguments.current.attributes[i].Label + '</th>';
    }
    html += '</tr></thead><tbody>';
    html += '<tr>';
    for (var j = 0; j < dialogArguments.current.attributes.length; j++) {
        html += '<td>' + Xrm.ShowDupes._getDisplayValue(dialogArguments.current.attributes[j]) + '</td>';
    }
    html += "</tr>";
    html += '</tbody><tfoot><tr></tr></tfoot></table>';
    $(html).appendTo('#current');
};

Xrm.ShowDupes._getDisplayValue = function (attribute) {
    switch (attribute.AttributeType) {
        case "customer":
        case "lookup":
            return (attribute.Value.Name === null || attribute.Value.Name === undefined) ? "" : attribute.Value.Name;
        case "picklist":
        case "state":
        case "owner":
        case "integer":
        case "string":
            return (attribute.Value === null) ? "" : attribute.Value;
        case "datetime":
            var date = new Date(attribute.Value);
            date = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " +
                ("0" + (date.getHours() + 1)).slice(-2) + ":" + ("0" + (date.getMinutes() + 1)).slice(-2);
            return date;
    }
    return "";
};